library iwindow;

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'config.dart';
import 'container.dart';
import 'layer.dart';

class IWindow {
  static final IWindow instance = IWindow._interval();
  factory IWindow() => instance;

  IWindow._interval() {
    config = IWindowConfig()..init();
  }

  late IWindowConfig config;
  static bool isShow({required String name}) {
    return instance._widgetData[name] != null;
  }

  Widget? get w {
    if (keys.isEmpty) return null;
    return _widgetData[keys.last];
  }

  Widget? getW(String name) {
    return _widgetData[name];
  }

  OverlayEntry? oe;

  BuildContext? ctx;
  Timer? _timer;

  VoidCallback? dismissAction;

  final Map<String, Widget> _widgetData = {};
  final List<String> keys = [];

  static Widget init(BuildContext ctx, Widget? child) {
    instance.ctx = ctx;
    return IWindowView(
      child: child,
    );
  }

  // *[name] 当前child唯一标识
  static Future<void> show(
    Widget child, {
    required String name,
    Duration? duration,
    AlignmentGeometry alignment = Alignment.center,
    VoidCallback? dismiss,
    bool isPan = false,
  }) async {
    instance._show(
      child,
      name: name,
      duration: duration,
      alignment: alignment,
      isPan: isPan,
      dismiss: dismiss,
    );
  }

  static Future<void> dismiss({required String name}) async {
    instance._dismiss(name: name);
  }

  Future<void> _show(
    Widget child, {
    required String name,
    Duration? duration,
    required AlignmentGeometry alignment,
    VoidCallback? dismiss,
    bool isPan = false,
  }) async {
    dismissAction = dismiss;
    if (oe == null) {
      return;
    }
    Completer<void> completer = Completer<void>();
    if (_widgetData[name] == null) {}
    final pc = IWindowContainer(
      completer: completer,
      duration: duration,
      alignment: alignment,
      isPan: isPan,
      child: child,
    );
    keys.add(name);
    _widgetData[name] = pc;

    completer.future.whenComplete(() {
      if (duration != null) {
        // _cancelTimer();
        // _timer = Timer(duration, () async {
        //   await dismiss();
        // });
      }
    });
    _markNeedsBuild();
    return completer.future;
  }

  Future<void> _dismiss({required String name}) async {
    if (!keys.contains(name)) {
      return;
    }
    if (dismissAction != null) {
      dismissAction!();
    }
    keys.remove(name);
    _widgetData.remove(name);
    _markNeedsBuild();
  }

  void _markNeedsBuild() {
    oe?.markNeedsBuild();
  }

  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
